// pages/me/walktohome/walktohome.js
import util from '../../../utils/utils';
import User from '../../../utils/user';
import {
  walktohomeHttp
} from '../../../api/walktohome';
import {
  HomeHttp
} from "../../../api/home";
const homeModel = new HomeHttp();
const walktoModel = new walktohomeHttp();
let videoAd = null;
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  autoAuth: false,
  TopPage: 1,
  pageSize: 10,
  totalNum: 0,
  pea_id: '', //添加幸运的id 用于双倍领取弹窗
  data: {
    welkBgImg: util.pageUrl +"mini/images/me/walk_bg.png",
    stepNum: 0, //微信运动步数
    isShowErrorPopup: false,
    errorPopupInfo: {},
    rulesShow: false, //赚豆规则内容
    popupAdvertising: true, //弹出层广告位
    walkInfo: {}, //首页信息
    bubbleData: [], //气泡数据
    pea_rate: '', //步数比例
    recommendGoods: [],
    bubbleanimationData: {},
    steFlag: true,
    adUnitId: 'adunit-b5fbbe96f27d0e64',
    intervalTime: 30, //更新步数间隔时间
    rewardedVideoAdFlag: false, //激励视频是否拉取成功
    isShowSignPopup: false, //获得翻倍提示框
    PeaDoublePea_add: 0, //翻倍获得豆数
    task: {
      "name": "任务大厅",
      "path": '/pages/task/index',
      "version": 1
    },
    recommendPage: 1,
  },
  initPage(options) {
    let userInfo = app.globalData.userInfo;
    this.setData({
      pea_rate: userInfo.common.pea_rate
    });
    let that = this;
    //添加好友
    this.AddStepFriendFun(options);
    //基本数据
    this.StepEarnBeanIndex();
    //获取推荐商品
    that.GetRecommendfun();
    this.setBubbleLocation();
    this.initAd();

    //获取当前时间戳
    let timestamp = new Date().getTime();
    let getWeRunDataTime = wx.getStorageSync('getWeRunDataTime');
    if (getWeRunDataTime) {
      let minutes = this.getYMDHMS(getWeRunDataTime);
      console.log('距你上次同步步数相隔' + minutes + '分钟');
      if (minutes > this.data.intervalTime) {
        //同步微信运动步数
        this.getWeRunDataFun();
        //存储该请求时间
        wx.setStorage({
          key: "getWeRunDataTime",
          data: timestamp
        });
      }
    } else {
      //同步微信运动步数
      this.getWeRunDataFun();
      wx.setStorage({
        key: "getWeRunDataTime",
        data: timestamp
      });
    }
    //测试翻倍奖励
    // this.pea_id = 27702;
    // this.setPopupFun(1,66);
  },
  AddStepFriendFun(options) {
    let that = this;
    let friend_uid = options.uid;
    let myuid = app.globalData.userInfo.uid;
    if (myuid == friend_uid) {
      return
    }
    walktoModel.AddStepFriend({
      friend_id: friend_uid
    }).then((res) => {
      if (res.status == 'ok') {
        that.StepEarnBeanIndex();
      }
    }).catch((err) => {
      console.log(`err`, err)
    })
  },
  getYMDHMS(getWeRunDataTime) {
    let timestamp = new Date().getTime();
    let leave1 = timestamp - getWeRunDataTime;
    //计算出相差天数
    let hourLevel = leave1 % (24 * 60 * 60 * 1000);
    let hours = Math.floor(hourLevel / (60 * 60 * 1000));
    //计算小时数
    let minutesLevel = hourLevel % (60 * 60 * 1000);
    return Math.floor(minutesLevel / (60 * 1000));
  },
  GetRecommendfun() {
    let that = this;
    let page = this.data.recommendPage;
    return homeModel.getGoodsRecommend({
      "client_type": 3,
      "page": page,
      "page_size": 20,
    }, false).then((res) => {
      res = this.getGoodsList(res.recommend_list);
      this.setData({
        recommendGoods: page === 1 ? res : this.data.recommendGoods.concat(res)
      })
    });
  },
  // 获取商品列表
  getGoodsList(res) {
    let i = 0;
    let goodslist = [];
    for (i; i < res.length; i++) {
      res[i]['goods']['price'] = res[i]['goods']['lowestPrice'];
      goodslist.push(res[i].goods)
    }
    return goodslist
  },
  //获取微信运动步数
  getWeRunDataFun(e) {
    let that = this;
    if (!this.data.steFlag) {
      util.msg('操作太频繁请稍后再试');
      return
    }
    that.setData({
      steFlag: false
    });
    let app = getApp();
    app.globalData.encryptKey = false;
    util.cache_remove('encryptKey');
    util.loading();
    User.getUserCode(function(code) {
      wx.getWeRunData({
        success(res) {
          // 拿 encryptedData 到开发者后台解密开放数据
          const encryptedData = res.encryptedData
          const iv = res.iv;
          let data = {
            encryptedData: encryptedData,
            iv: iv,
            key: code.key,
          }
          util.request({
            url: 's/luckdraw/UpdateStep',
            handle: true,
            loading: true,
            data: data,
            callback: function(resdata) {
              let res = resdata.res;
              if (res.status = 'ok') {
                that.initPage(that.options);
                if (res.step == 0) {
                  util.msg('未获取到步数，先去微信运动看看吧');
                  wx.removeStorage({
                    key: 'getWeRunDataTime',
                    success(res) {
                      console.log(res);
                    }
                  })
                }
                that.setData({
                  stepNum: res.step
                });
              }
            }
          })
        },
        fail(err) {
          util.msg('获取运动步数失败！');
          console.log('err', err)
        }
      })
    }, false, 2);
    //重置steFlag
    setTimeout(() => {
      that.setData({
        steFlag: true
      });
    }, 5000);
  },

  //获取首页数据
  StepEarnBeanIndex: function() {
    let that = this;
    walktoModel.StepEarnBeanIndex({}).then((res) => {
      let data = res;
      // let _data =[
      //   {
      //     "id": 1,	//亲友id
      //     "name": "风华", //名称
      //     "avatar": "https://img.quzhao.com/uploads/oss/avatar/201911/19/145714y6l5Wg2w.jpg",
      //          					//头像
      //     "step": 13547,//步数
      //     "bean": 66	//可领取幸运豆数量
      //   },
      //   {
      //     "id": 2,	//亲友id
      //     "name": "风华", //名称
      //     "avatar": "https://img.quzhao.com/uploads/oss/avatar/201911/19/145714y6l5Wg2w.jpg",
      //          					//头像
      //     "step": 13547,//步数
      //     "bean": 66	//可领取幸运豆数量
      //   },
      // ];
      // data.friends_ranking_list = _data;
      that.setData({
        walkInfo: data,
        stepNum: data.step_num,
      });
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }).catch((err) => {
      console.log(`err`, err)
    })

  },
  toPage: function(event) {
    util.toPage(event);
  },
  //排行榜单滚动底部刷新
  scrollupper: function() {
    console.log("到顶了");
  },
  //排行榜单滚动底部加载更多
  lscrollower: function() {
    console.log("到底了");
  },
  //新手任务
  advertisingFun(e) {
    this.setPopupFun(3, 100);
  },
  //关闭弹窗
  ShutdownFun: function(e) {
    this.setData({
      isShowErrorPopup: false
    });
  },
  //收取好友分成
  StepAddFriendPean: function(e) {
    let that = this;
    let _data = e.currentTarget.dataset;
    let _index = _data.index;
    let _walkInfo = that.data.walkInfo;
    let _beansNum = _walkInfo.friends_ranking_list[_index].bean;
    if (_beansNum <= 0) {
      return false;
    }
    _walkInfo.friends_ranking_list[_index].bean = 0;
    walktoModel.getAddFriendPean({
      friend_id: _data.friendid
    }).then((res) => {
      _walkInfo.my_bean = res.pea_blance;
      that.pea_id = res.pea_id;
      if (res.pea_id && res.pea_id !== 0) {
        that.setPopupFun(1, _beansNum);
      }
      that.setData({
        walkInfo: _walkInfo
      });
    }).catch((err) => {
      console.log(`err`, err)
    });
  },
  //领取自己走路豆子
  onbubblefun: function(e) {
    let that = this;
    let _walkInfo = that.data.walkInfo;
    let _beansNum = that.data.walkInfo.bean_num
    walktoModel.getMyStepAddPean({}).then((res) => {
      _walkInfo.my_bean = res.pea_blance;
      _walkInfo.bean_num = 0;
      that.pea_id = res.pea_id;
      // 没有pea_id不弹出翻倍奖励弹窗
      if (res.pea_id && res.pea_id !== 0) {
        that.setPopupFun(1, _beansNum);
      }
      that.setData({
        walkInfo: _walkInfo
      });
    }).catch((err) => {
      console.log(`err`, err)
    })
  },
  //判断弹窗类型
  setPopupFun(num, beansNum) {
    let userInfo = app.globalData.userInfo;
    let myDou = userInfo.common.pea_blance
    let _obtainNum = 500;

    let _Data = {};
    switch (num) { 
      case 1: //获得翻倍
        this.setData({
          errorPopupInfo: {
            img: '/images/me/wallk-popup-img02.png',
            des: "获得" + beansNum + "幸运豆",
            btnText: "幸运豆翻倍x2",
            myDou: myDou,
            btnType: 3
          }
        })
        break
      case 2: //参与失败
        this.setData({
          errorPopupInfo: {
            img: '/images/me/wallk-popup-img01.png',
            title: "参与失败",
            des: "您的幸运豆余额不足，去获取幸运豆",
            btnText: "领取1000幸运豆",
            myDou: myDou,
            btnType: 1
          }
        })
        break
      case 3: //获得多少幸运豆
        this.setData({
          errorPopupInfo: {
            img: '/images/me/wallk-popup-img02.png',
            title: '获得' + _obtainNum + '幸运豆',
            des: '恭喜您获得了' + _obtainNum + '幸运豆的领取资格， 在完成任务后即可获得',
            btnText: "去完成任务",
            myDou: myDou,
            btnType: 1
          }
        })
        break
      case 4: //参与秒杀成功
        this.setData({
          errorPopupInfo: {
            img: '/images/me/wallk-popup-img03.png',
            title: '参与秒杀成功',
            des: '您已成功获得该商品秒杀资格，赶紧下单购买吧支付失败,或放弃秒杀资格,幸运豆将原路返回',
            btnText: "立即前往",
            myDou: myDou,
            btnType: 4
          }
        })
        break
      case 5: //走路获得多少豆
        this.setData({
          errorPopupInfo: {
            img: '/images/me/wallk-popup-img03.png',
            des: '走路获得' + _obtainNum + '幸运豆',
            btnText: "分享给好友增加幸运豆",
            myDou: myDou,
            btnType: 2
          }
        })
        break
    }
    this.setData({
      isShowErrorPopup: true
    })
  },
  onClickPopupBtn() {
    let self = this;
    let data = this.data.errorPopupInfo
    if (data.btnType === 1) {
      wx.switchTab({
        url: '/pages/task/index',
      })
    }
    if (data.btnType === 3) {
      self.openAdShow()
    }
  },
  /**
   * 下拉刷新页面数据
   * @returns {boolean}
   */
  onPullDownRefresh: function() {
    this.initPage(this.options);
  },
  adLoad() {
    console.log('Banner 广告加载成功')
  },
  adError(err) {
    console.log('Banner 广告加载失败', err)
  },
  adClose() {
    console.log('Banner 广告关闭')
  },
  //设置气泡位置
  setBubbleLocation: function() {
    let graph = [{
      x: 233,
      y: 210
    }, {
      x: 180,
      y: 224
    }, {
      x: 119,
      y: 228
    }];
    this.setData({
      bubbleData: graph
    });
  },
  onCloseRulesShow() {
    this.setData({
      rulesShow: true
    });
  },
  onCloseRulesHide() {
    this.setData({
      rulesShow: false
    });
  },
  onChange(event) {
    console.log(event);
    this.setData({
      activeNames: event.detail
    });
  },
  //
  onShareAppMessage: function(res) {
    let _static_host = this.data.static_host;
    console.log(_static_host)
    let ekey = this.data.walkInfo.ekey;
    let uid = app.globalData.userInfo.uid;
    let nickName = app.globalData.userInfo && app.globalData.userInfo.nickname ? app.globalData.userInfo.nickname : ''
    let nickNameText = nickName ? `${nickName}@您，` : ''
    // if (res.from === 'button') {
    console.log()
    return {
      title: `${nickNameText}快来这里走路能领幸运豆，下单可抵现金哦！`,
      path: 'pages/me/walktohome/walktohome?ekey=' + ekey + '&uid=' + uid,
      imageUrl: `${_static_host}/images/share/walk.png?t=23`
    }
    //}
  },
  initAd: function() {

    let that = this;
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: that.data.adUnitId
      })
      videoAd.onLoad(() => {
        this.rewardedVideoAdFlag = true;
        console.log('激励视屏加载成功');
      })
      videoAd.onError((err) => {
        this.rewardedVideoAdFlag = false;
        console.log(err);
      })
      videoAd.onClose((status) => {
        if (status && status.isEnded || status === undefined) {
          that.WatchTheFinish(); //看完关闭
        } else {
          that.interrupt(); //中途关闭
        }
      })
    }

  },
  //正常播放结束，下发奖励
  WatchTheFinish: function() {
    this.getPeaDoubleFun(1);
    this.ShutdownFun();
  },
  //播放中途退出，进行提示
  interrupt: function() {
    this.getPeaDoubleFun(2);
    this.ShutdownFun();
  },
  //打开双倍按钮
  openAdShow() {
    console.log(11)
    let that = this;
    this.ShutdownFun();
    console.log('打开激励视频');
    if (!this.rewardedVideoAdFlag) {
      util.msg('今天观看视频获得奖励次数已达限');
      return
    }
    if (videoAd) {
      videoAd.show().catch(() => {
        // 失败重试
        videoAd.load()
          .then(() => videoAd.show())
          .catch(err => {
            that.getPeaDoubleFun(2);
            console.log('激励视频 广告显示失败')
          })
      })
    }
  },
  //豆子翻倍
  getPeaDoubleFun(state) {
    //state   1观看完成   2中途关闭广告
    let that = this;
    if (!that.pea_id) {
      util.msg('pea_id缺失');
      this.ShutdownFun();
      return
    }
    let msgText = '获得奖励';
    if (state == 2) {
      msgText = '中途退出未获得翻倍奖励';
    }
    walktoModel.getPeaDouble({
      ad_id: that.data.adUnitId,
      ad_type: 1,
      pea_id: that.pea_id,
      complete: state
    }).then((res) => {
      console.log(res);
      let _walkInfo = that.data.walkInfo;
      _walkInfo.my_bean = res.pea_blance;
      util.msg(msgText);
      that.setData({
        walkInfo: _walkInfo,
        PeaDoublePea_add: res.pea_add
      });
      that.ShutdownFun();
      //没有则显示签到获得豆子数
      if (res.pea_add && res.pea_add > 0) {
        this.setData({
          isShowSignPopup: true
        });
        let timer = setTimeout(() => {
          that.setData({
            isShowSignPopup: false
          });
          clearTimeout(timer)
        }, 3000)
      }
    }).catch((err) => {
      console.log(`err`, err)
    })

  },
  //页面上拉
  onReachBottom: function() {
    +this.setData({
      recommendPage: this.data.recommendPage + 1
    });
    this.GetRecommendfun()
  }
});
